3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
21 use MediaWiki\MediaWikiServices
;
24 * Base class for language conversion.
27 * @author Zhengzhu Feng <zhengzhu@gmail.com>
28 * @author fdcn <fdcn64@gmail.com>
29 * @author shinjiman <shinjiman@gmail.com>
30 * @author PhiLiP <philip.npc@gmail.com>
32 class LanguageConverter
{
34 * languages supporting variants
38 static public $languagesWithVariants = [
51 public $mMainLanguageCode;
57 public $mVariantFallbacks;
58 public $mVariantNames;
59 public $mTablesLoaded = false;
61 // 'bidirectional' 'unidirectional' 'disable' for each variant
66 public $mDescCodeSep = ':', $mDescVarSep = ';';
67 public $mUcfirst = false;
68 public $mConvRuleTitle = false;
71 public $mHeaderVariant;
72 public $mMaxDepth = 10;
73 public $mVarSeparatorPattern;
75 const CACHE_VERSION_KEY
= 'VERSION 7';
78 * @param Language $langobj
79 * @param string $maincode The main language code of this language
80 * @param string[] $variants The supported variants of this language
81 * @param array $variantfallbacks The fallback language of each variant
82 * @param array $flags Defining the custom strings that maps to the flags
83 * @param array $manualLevel Limit for supported variants
85 public function __construct( $langobj, $maincode, $variants = [],
86 $variantfallbacks = [], $flags = [],
88 global $wgDisabledVariants;
89 $this->mLangObj
= $langobj;
90 $this->mMainLanguageCode
= $maincode;
91 $this->mVariants
= array_diff( $variants, $wgDisabledVariants );
92 $this->mVariantFallbacks
= $variantfallbacks;
93 $this->mVariantNames
= Language
::fetchLanguageNames();
95 // 'S' show converted text
96 // '+' add rules for alltext
97 // 'E' the gave flags is error
98 // these flags above are reserved for program
99 'A' => 'A', // add rule for convert code (all text convert)
100 'T' => 'T', // title convert
101 'R' => 'R', // raw content
102 'D' => 'D', // convert description (subclass implement)
103 '-' => '-', // remove convert (not implement)
104 'H' => 'H', // add rule for convert code (but no display in placed code)
105 'N' => 'N', // current variant name
107 $this->mFlags
= array_merge( $defaultflags, $flags );
108 foreach ( $this->mVariants
as $v ) {
109 if ( array_key_exists( $v, $manualLevel ) ) {
110 $this->mManualLevel
[$v] = $manualLevel[$v];
112 $this->mManualLevel
[$v] = 'bidirectional';
114 $this->mFlags
[$v] = $v;
119 * Get all valid variants.
120 * Call this instead of using $this->mVariants directly.
122 * @return string[] Contains all valid variants
124 public function getVariants() {
125 return $this->mVariants
;
129 * In case some variant is not defined in the markup, we need
130 * to have some fallback. For example, in zh, normally people
131 * will define zh-hans and zh-hant, but less so for zh-sg or zh-hk.
132 * when zh-sg is preferred but not defined, we will pick zh-hans
133 * in this case. Right now this is only used by zh.
135 * @param string $variant The language code of the variant
136 * @return string|array The code of the fallback language or the
137 * main code if there is no fallback
139 public function getVariantFallbacks( $variant ) {
140 if ( isset( $this->mVariantFallbacks
[$variant] ) ) {
141 return $this->mVariantFallbacks
[$variant];
143 return $this->mMainLanguageCode
;
147 * Get the title produced by the conversion rule.
148 * @return string The converted title text
150 public function getConvRuleTitle() {
151 return $this->mConvRuleTitle
;
155 * Get preferred language variant.
156 * @return string The preferred language code
158 public function getPreferredVariant() {
159 global $wgDefaultLanguageVariant, $wgUser;
161 $req = $this->getURLVariant();
163 if ( $wgUser->isSafeToLoad() && $wgUser->isLoggedIn() && !$req ) {
164 $req = $this->getUserVariant();
166 $req = $this->getHeaderVariant();
169 if ( $wgDefaultLanguageVariant && !$req ) {
170 $req = $this->validateVariant( $wgDefaultLanguageVariant );
173 // This function, unlike the other get*Variant functions, is
174 // not memoized (i.e. there return value is not cached) since
175 // new information might appear during processing after this
177 if ( $this->validateVariant( $req ) ) {
180 return $this->mMainLanguageCode
;
184 * Get default variant.
185 * This function would not be affected by user's settings
186 * @return string The default variant code
188 public function getDefaultVariant() {
189 global $wgDefaultLanguageVariant;
191 $req = $this->getURLVariant();
194 $req = $this->getHeaderVariant();
197 if ( $wgDefaultLanguageVariant && !$req ) {
198 $req = $this->validateVariant( $wgDefaultLanguageVariant );
204 return $this->mMainLanguageCode
;
208 * Validate the variant
209 * @param string $variant The variant to validate
210 * @return mixed Returns the variant if it is valid, null otherwise
212 public function validateVariant( $variant = null ) {
213 if ( $variant !== null && in_array( $variant, $this->mVariants
) ) {
220 * Get the variant specified in the URL
222 * @return mixed Variant if one found, false otherwise.
224 public function getURLVariant() {
227 if ( $this->mURLVariant
) {
228 return $this->mURLVariant
;
231 // see if the preference is set in the request
232 $ret = $wgRequest->getText( 'variant' );
235 $ret = $wgRequest->getVal( 'uselang' );
238 $this->mURLVariant
= $this->validateVariant( $ret );
239 return $this->mURLVariant
;
243 * Determine if the user has a variant set.
245 * @return mixed Variant if one found, false otherwise.
247 protected function getUserVariant() {
248 global $wgUser, $wgContLang;
250 // memoizing this function wreaks havoc on parserTest.php
252 if ( $this->mUserVariant ) {
253 return $this->mUserVariant;
257 // Get language variant preference from logged in users
258 // Don't call this on stub objects because that causes infinite
259 // recursion during initialisation
260 if ( !$wgUser->isSafeToLoad() ) {
263 if ( $wgUser->isLoggedIn() ) {
264 if ( $this->mMainLanguageCode
== $wgContLang->getCode() ) {
265 $ret = $wgUser->getOption( 'variant' );
267 $ret = $wgUser->getOption( 'variant-' . $this->mMainLanguageCode
);
270 // figure out user lang without constructing wgLang to avoid
271 // infinite recursion
272 $ret = $wgUser->getOption( 'language' );
275 $this->mUserVariant
= $this->validateVariant( $ret );
276 return $this->mUserVariant
;
280 * Determine the language variant from the Accept-Language header.
282 * @return mixed Variant if one found, false otherwise.
284 protected function getHeaderVariant() {
287 if ( $this->mHeaderVariant
) {
288 return $this->mHeaderVariant
;
291 // see if some supported language variant is set in the
293 $languages = array_keys( $wgRequest->getAcceptLang() );
294 if ( empty( $languages ) ) {
298 $fallbackLanguages = [];
299 foreach ( $languages as $language ) {
300 $this->mHeaderVariant
= $this->validateVariant( $language );
301 if ( $this->mHeaderVariant
) {
305 // To see if there are fallbacks of current language.
306 // We record these fallback variants, and process
308 $fallbacks = $this->getVariantFallbacks( $language );
309 if ( is_string( $fallbacks ) && $fallbacks !== $this->mMainLanguageCode
) {
310 $fallbackLanguages[] = $fallbacks;
311 } elseif ( is_array( $fallbacks ) ) {
313 array_merge( $fallbackLanguages, $fallbacks );
317 if ( !$this->mHeaderVariant
) {
318 // process fallback languages now
319 $fallback_languages = array_unique( $fallbackLanguages );
320 foreach ( $fallback_languages as $language ) {
321 $this->mHeaderVariant
= $this->validateVariant( $language );
322 if ( $this->mHeaderVariant
) {
328 return $this->mHeaderVariant
;
332 * Dictionary-based conversion.
333 * This function would not parse the conversion rules.
334 * If you want to parse rules, try to use convert() or
337 * @param string $text The text to be converted
338 * @param bool|string $toVariant The target language code
339 * @return string The converted text
341 public function autoConvert( $text, $toVariant = false ) {
346 $toVariant = $this->getPreferredVariant();
352 if ( $this->guessVariant( $text, $toVariant ) ) {
356 /* we convert everything except:
357 * 1. HTML markups (anything between < and >)
359 * 3. placeholders created by the parser
361 $marker = '|' . Parser
::MARKER_PREFIX
. '[\-a-zA-Z0-9]+';
363 // this one is needed when the text is inside an HTML markup
364 $htmlfix = '|<[^>]+$|^[^<>]*>';
366 // disable convert to variants between <code> tags
367 $codefix = '<code>.+?<\/code>|';
368 // disable conversion of <script> tags
369 $scriptfix = '<script.*?>.*?<\/script>|';
370 // disable conversion of <pre> tags
371 $prefix = '<pre.*?>.*?<\/pre>|';
373 $reg = '/' . $codefix . $scriptfix . $prefix .
374 '<[^>]+>|&[a-zA-Z#][a-z0-9]+;' . $marker . $htmlfix . '/s';
379 // Guard against delimiter nulls in the input
380 // (should never happen: see T159174)
381 $text = str_replace( "\000", '', $text );
383 $markupMatches = null;
384 $elementMatches = null;
385 while ( $startPos < strlen( $text ) ) {
386 if ( preg_match( $reg, $text, $markupMatches, PREG_OFFSET_CAPTURE
, $startPos ) ) {
387 $elementPos = $markupMatches[0][1];
388 $element = $markupMatches[0][0];
390 $elementPos = strlen( $text );
394 // Queue the part before the markup for translation in a batch
395 $sourceBlob .= substr( $text, $startPos, $elementPos - $startPos ) . "\000";
397 // Advance to the next position
398 $startPos = $elementPos +
strlen( $element );
400 // Translate any alt or title attributes inside the matched element
402 && preg_match( '/^(<[^>\s]*)\s([^>]*)(.*)$/', $element, $elementMatches )
404 $attrs = Sanitizer
::decodeTagAttributes( $elementMatches[2] );
406 foreach ( [ 'title', 'alt' ] as $attrName ) {
407 if ( !isset( $attrs[$attrName] ) ) {
410 $attr = $attrs[$attrName];
411 // Don't convert URLs
412 if ( !strpos( $attr, '://' ) ) {
413 $attr = $this->recursiveConvertTopLevel( $attr, $toVariant );
416 if ( $attr !== $attrs[$attrName] ) {
417 $attrs[$attrName] = $attr;
422 $element = $elementMatches[1] . Html
::expandAttributes( $attrs ) .
426 $literalBlob .= $element . "\000";
429 // Do the main translation batch
430 $translatedBlob = $this->translate( $sourceBlob, $toVariant );
432 // Put the output back together
433 $translatedIter = StringUtils
::explode( "\000", $translatedBlob );
434 $literalIter = StringUtils
::explode( "\000", $literalBlob );
436 while ( $translatedIter->valid() && $literalIter->valid() ) {
437 $output .= $translatedIter->current();
438 $output .= $literalIter->current();
439 $translatedIter->next();
440 $literalIter->next();
447 * Translate a string to a variant.
448 * Doesn't parse rules or do any of that other stuff, for that use
449 * convert() or convertTo().
451 * @param string $text Text to convert
452 * @param string $variant Variant language code
453 * @return string Translated text
455 public function translate( $text, $variant ) {
456 // If $text is empty or only includes spaces, do nothing
457 // Otherwise translate it
458 if ( trim( $text ) ) {
460 $text = $this->mTables
[$variant]->replace( $text );
466 * Call translate() to convert text to all valid variants.
468 * @param string $text The text to be converted
469 * @return array Variant => converted text
471 public function autoConvertToAllVariants( $text ) {
475 foreach ( $this->mVariants
as $variant ) {
476 $ret[$variant] = $this->translate( $text, $variant );
483 * Apply manual conversion rules.
485 * @param ConverterRule $convRule
487 protected function applyManualConv( $convRule ) {
488 // Use syntax -{T|zh-cn:TitleCN; zh-tw:TitleTw}- to custom
490 // T26072: $mConvRuleTitle was overwritten by other manual
491 // rule(s) not for title, this breaks the title conversion.
492 $newConvRuleTitle = $convRule->getTitle();
493 if ( $newConvRuleTitle ) {
494 // So I add an empty check for getTitle()
495 $this->mConvRuleTitle
= $newConvRuleTitle;
498 // merge/remove manual conversion rules to/from global table
499 $convTable = $convRule->getConvTable();
500 $action = $convRule->getRulesAction();
501 foreach ( $convTable as $variant => $pair ) {
502 if ( !$this->validateVariant( $variant ) ) {
506 if ( $action == 'add' ) {
507 // More efficient than array_merge(), about 2.5 times.
508 foreach ( $pair as $from => $to ) {
509 $this->mTables
[$variant]->setPair( $from, $to );
511 } elseif ( $action == 'remove' ) {
512 $this->mTables
[$variant]->removeArray( $pair );
518 * Auto convert a Title object to a readable string in the
521 * @param Title $title A object of Title
522 * @return string Converted title text
524 public function convertTitle( $title ) {
525 $variant = $this->getPreferredVariant();
526 $index = $title->getNamespace();
527 if ( $index !== NS_MAIN
) {
528 $text = $this->convertNamespace( $index, $variant ) . ':';
532 $text .= $this->translate( $title->getText(), $variant );
537 * Get the namespace display name in the preferred variant.
539 * @param int $index Namespace id
540 * @param string|null $variant Variant code or null for preferred variant
541 * @return string Namespace name for display
543 public function convertNamespace( $index, $variant = null ) {
544 if ( $index === NS_MAIN
) {
548 if ( $variant === null ) {
549 $variant = $this->getPreferredVariant();
552 $cache = MediaWikiServices
::getInstance()->getLocalServerObjectCache();
553 $key = $cache->makeKey( 'languageconverter', 'namespace-text', $index, $variant );
554 $nsVariantText = $cache->get( $key );
555 if ( $nsVariantText !== false ) {
556 return $nsVariantText;
559 // First check if a message gives a converted name in the target variant.
560 $nsConvMsg = wfMessage( 'conversion-ns' . $index )->inLanguage( $variant );
561 if ( $nsConvMsg->exists() ) {
562 $nsVariantText = $nsConvMsg->plain();
565 // Then check if a message gives a converted name in content language
566 // which needs extra translation to the target variant.
567 if ( $nsVariantText === false ) {
568 $nsConvMsg = wfMessage( 'conversion-ns' . $index )->inContentLanguage();
569 if ( $nsConvMsg->exists() ) {
570 $nsVariantText = $this->translate( $nsConvMsg->plain(), $variant );
574 if ( $nsVariantText === false ) {
575 // No message exists, retrieve it from the target variant's namespace names.
576 $langObj = $this->mLangObj
->factory( $variant );
577 $nsVariantText = $langObj->getFormattedNsText( $index );
580 $cache->set( $key, $nsVariantText, 60 );
582 return $nsVariantText;
586 * Convert text to different variants of a language. The automatic
587 * conversion is done in autoConvert(). Here we parse the text
588 * marked with -{}-, which specifies special conversions of the
589 * text that can not be accomplished in autoConvert().
591 * Syntax of the markup:
592 * -{code1:text1;code2:text2;...}- or
593 * -{flags|code1:text1;code2:text2;...}- or
594 * -{text}- in which case no conversion should take place for text
596 * @param string $text Text to be converted
597 * @return string Converted text
599 public function convert( $text ) {
600 $variant = $this->getPreferredVariant();
601 return $this->convertTo( $text, $variant );
605 * Same as convert() except a extra parameter to custom variant.
607 * @param string $text Text to be converted
608 * @param string $variant The target variant code
609 * @return string Converted text
611 public function convertTo( $text, $variant ) {
612 global $wgDisableLangConversion;
613 if ( $wgDisableLangConversion ) {
616 // Reset converter state for a new converter run.
617 $this->mConvRuleTitle
= false;
618 return $this->recursiveConvertTopLevel( $text, $variant );
622 * Recursively convert text on the outside. Allow to use nested
623 * markups to custom rules.
625 * @param string $text Text to be converted
626 * @param string $variant The target variant code
627 * @param int $depth Depth of recursion
628 * @return string Converted text
630 protected function recursiveConvertTopLevel( $text, $variant, $depth = 0 ) {
633 $length = strlen( $text );
634 $shouldConvert = !$this->guessVariant( $text, $variant );
636 while ( $startPos < $length ) {
637 $pos = strpos( $text, '-{', $startPos );
639 if ( $pos === false ) {
640 // No more markup, append final segment
641 $fragment = substr( $text, $startPos );
642 $out .= $shouldConvert ?
$this->autoConvert( $fragment, $variant ) : $fragment;
647 // Append initial segment
648 $fragment = substr( $text, $startPos, $pos - $startPos );
649 $out .= $shouldConvert ?
$this->autoConvert( $fragment, $variant ) : $fragment;
654 // Do recursive conversion
655 $out .= $this->recursiveConvertRule( $text, $variant, $startPos, $depth +
1 );
662 * Recursively convert text on the inside.
664 * @param string $text Text to be converted
665 * @param string $variant The target variant code
666 * @param int $startPos
667 * @param int $depth Depth of recursion
669 * @throws MWException
670 * @return string Converted text
672 protected function recursiveConvertRule( $text, $variant, &$startPos, $depth = 0 ) {
673 // Quick sanity check (no function calls)
674 if ( $text[$startPos] !== '-' ||
$text[$startPos +
1] !== '{' ) {
675 throw new MWException( __METHOD__
. ': invalid input string' );
680 $warningDone = false;
681 $length = strlen( $text );
683 while ( $startPos < $length ) {
685 preg_match( '/-\{|\}-/', $text, $m, PREG_OFFSET_CAPTURE
, $startPos );
695 // Append initial segment
696 $inner .= substr( $text, $startPos, $pos - $startPos );
704 if ( $depth >= $this->mMaxDepth
) {
706 if ( !$warningDone ) {
707 $inner .= '<span class="error">' .
708 wfMessage( 'language-converter-depth-warning' )
709 ->numParams( $this->mMaxDepth
)->inContentLanguage()->text() .
716 // Recursively parse another rule
717 $inner .= $this->recursiveConvertRule( $text, $variant, $startPos, $depth +
1 );
722 $rule = new ConverterRule( $inner, $this );
723 $rule->parse( $variant );
724 $this->applyManualConv( $rule );
725 return $rule->getDisplay();
727 throw new MWException( __METHOD__
. ': invalid regex match' );
732 if ( $startPos < $length ) {
733 $inner .= substr( $text, $startPos );
736 return '-{' . $this->autoConvert( $inner, $variant );
740 * If a language supports multiple variants, it is possible that
741 * non-existing link in one variant actually exists in another variant.
742 * This function tries to find it. See e.g. LanguageZh.php
743 * The input parameters may be modified upon return
745 * @param string &$link The name of the link
746 * @param Title &$nt The title object of the link
747 * @param bool $ignoreOtherCond To disable other conditions when
748 * we need to transclude a template or update a category's link
750 public function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) {
751 # If the article has already existed, there is no need to
752 # check it again, otherwise it may cause a fault.
753 if ( is_object( $nt ) && $nt->exists() ) {
757 global $wgDisableLangConversion, $wgDisableTitleConversion, $wgRequest;
758 $isredir = $wgRequest->getText( 'redirect', 'yes' );
759 $action = $wgRequest->getText( 'action' );
760 if ( $action == 'edit' && $wgRequest->getBool( 'redlink' ) ) {
763 $linkconvert = $wgRequest->getText( 'linkconvert', 'yes' );
764 $disableLinkConversion = $wgDisableLangConversion
765 ||
$wgDisableTitleConversion;
766 $linkBatch = new LinkBatch();
770 if ( $disableLinkConversion ||
771 ( !$ignoreOtherCond &&
774 ||
$action == 'submit'
775 ||
$linkconvert == 'no' ) ) ) {
779 if ( is_object( $nt ) ) {
780 $ns = $nt->getNamespace();
783 $variants = $this->autoConvertToAllVariants( $link );
784 if ( !$variants ) { // give up
790 foreach ( $variants as $v ) {
792 $varnt = Title
::newFromText( $v, $ns );
793 if ( !is_null( $varnt ) ) {
794 $linkBatch->addObj( $varnt );
800 // fetch all variants in single query
801 $linkBatch->execute();
803 foreach ( $titles as $varnt ) {
804 if ( $varnt->getArticleID() > 0 ) {
806 $link = $varnt->getText();
813 * Returns language specific hash options.
817 public function getExtraHashOptions() {
818 $variant = $this->getPreferredVariant();
820 return '!' . $variant;
824 * Guess if a text is written in a variant. This should be implemented in subclasses.
826 * @param string $text The text to be checked
827 * @param string $variant Language code of the variant to be checked for
828 * @return bool True if $text appears to be written in $variant, false if not
830 * @author Nikola Smolenski <smolensk@eunet.rs>
833 public function guessVariant( $text, $variant ) {
838 * Load default conversion tables.
839 * This method must be implemented in derived class.
842 * @throws MWException
844 function loadDefaultTables() {
845 $class = static::class;
846 throw new MWException( "Must implement loadDefaultTables() method in class $class" );
850 * Load conversion tables either from the cache or the disk.
852 * @param bool $fromCache Load from memcached? Defaults to true.
854 function loadTables( $fromCache = true ) {
855 global $wgLanguageConverterCacheType;
857 if ( $this->mTablesLoaded
) {
861 $this->mTablesLoaded
= true;
862 $this->mTables
= false;
863 $cache = ObjectCache
::getInstance( $wgLanguageConverterCacheType );
864 $cacheKey = $cache->makeKey( 'conversiontables', $this->mMainLanguageCode
);
866 $this->mTables
= $cache->get( $cacheKey );
868 if ( !$this->mTables ||
!array_key_exists( self
::CACHE_VERSION_KEY
, $this->mTables
) ) {
869 // not in cache, or we need a fresh reload.
870 // We will first load the default tables
871 // then update them using things in MediaWiki:Conversiontable/*
872 $this->loadDefaultTables();
873 foreach ( $this->mVariants
as $var ) {
874 $cached = $this->parseCachedTable( $var );
875 $this->mTables
[$var]->mergeArray( $cached );
878 $this->postLoadTables();
879 $this->mTables
[self
::CACHE_VERSION_KEY
] = true;
881 $cache->set( $cacheKey, $this->mTables
, 43200 );
886 * Hook for post processing after conversion tables are loaded.
888 function postLoadTables() {
892 * Reload the conversion tables.
894 * Also used by test suites which need to reset the converter state.
898 private function reloadTables() {
899 if ( $this->mTables
) {
900 unset( $this->mTables
);
903 $this->mTablesLoaded
= false;
904 $this->loadTables( false );
908 * Parse the conversion table stored in the cache.
910 * The tables should be in blocks of the following form:
917 * To make the tables more manageable, subpages are allowed
918 * and will be parsed recursively if $recursive == true.
920 * @param string $code Language code
921 * @param string $subpage Subpage name
922 * @param bool $recursive Parse subpages recursively? Defaults to true.
926 function parseCachedTable( $code, $subpage = '', $recursive = true ) {
929 $key = 'Conversiontable/' . $code;
931 $key .= '/' . $subpage;
933 if ( array_key_exists( $key, $parsed ) ) {
937 $parsed[$key] = true;
939 if ( $subpage === '' ) {
940 $txt = MessageCache
::singleton()->getMsgFromNamespace( $key, $code );
943 $title = Title
::makeTitleSafe( NS_MEDIAWIKI
, $key );
944 if ( $title && $title->exists() ) {
945 $revision = Revision
::newFromTitle( $title );
947 if ( $revision->getContentModel() == CONTENT_MODEL_WIKITEXT
) {
948 $txt = $revision->getContent( Revision
::RAW
)->getNativeData();
951 // @todo in the future, use a specialized content model, perhaps based on json!
956 # Nothing to parse if there's no text
957 if ( $txt === false ||
$txt === null ||
$txt === '' ) {
961 // get all subpage links of the form
962 // [[MediaWiki:Conversiontable/zh-xx/...|...]]
963 $linkhead = $this->mLangObj
->getNsText( NS_MEDIAWIKI
) .
965 $subs = StringUtils
::explode( '[[', $txt );
967 foreach ( $subs as $sub ) {
968 $link = explode( ']]', $sub, 2 );
969 if ( count( $link ) != 2 ) {
972 $b = explode( '|', $link[0], 2 );
973 $b = explode( '/', trim( $b[0] ), 3 );
974 if ( count( $b ) == 3 ) {
980 if ( $b[0] == $linkhead && $b[1] == $code ) {
981 $sublinks[] = $sublink;
985 // parse the mappings in this page
986 $blocks = StringUtils
::explode( '-{', $txt );
989 foreach ( $blocks as $block ) {
991 // Skip the part before the first -{
995 $mappings = explode( '}-', $block, 2 )[0];
996 $stripped = str_replace( [ "'", '"', '*', '#' ], '', $mappings );
997 $table = StringUtils
::explode( ';', $stripped );
998 foreach ( $table as $t ) {
999 $m = explode( '=>', $t, 3 );
1000 if ( count( $m ) != 2 ) {
1003 // trim any trailling comments starting with '//'
1004 $tt = explode( '//', $m[1], 2 );
1005 $ret[trim( $m[0] )] = trim( $tt[0] );
1009 // recursively parse the subpages
1011 foreach ( $sublinks as $link ) {
1012 $s = $this->parseCachedTable( $code, $link, $recursive );
1017 if ( $this->mUcfirst
) {
1018 foreach ( $ret as $k => $v ) {
1019 $ret[$this->mLangObj
->ucfirst( $k )] = $this->mLangObj
->ucfirst( $v );
1026 * Enclose a string with the "no conversion" tag. This is used by
1027 * various functions in the Parser.
1029 * @param string $text Text to be tagged for no conversion
1030 * @param bool $noParse Unused
1031 * @return string The tagged text
1033 public function markNoConversion( $text, $noParse = false ) {
1034 # don't mark if already marked
1035 if ( strpos( $text, '-{' ) ||
strpos( $text, '}-' ) ) {
1039 $ret = "-{R|$text}-";
1044 * Convert the sorting key for category links. This should make different
1045 * keys that are variants of each other map to the same key.
1047 * @param string $key
1051 function convertCategoryKey( $key ) {
1056 * Refresh the cache of conversion tables when
1057 * MediaWiki:Conversiontable* is updated.
1059 * @param Title $titleobj The Title of the page being updated
1061 public function updateConversionTable( Title
$titleobj ) {
1062 if ( $titleobj->getNamespace() == NS_MEDIAWIKI
) {
1063 $title = $titleobj->getDBkey();
1064 $t = explode( '/', $title, 3 );
1066 if ( $c > 1 && $t[0] == 'Conversiontable' ) {
1067 if ( $this->validateVariant( $t[1] ) ) {
1068 $this->reloadTables();
1075 * Get the cached separator pattern for ConverterRule::parseRules()
1078 function getVarSeparatorPattern() {
1079 if ( is_null( $this->mVarSeparatorPattern
) ) {
1080 // varsep_pattern for preg_split:
1081 // text should be splited by ";" only if a valid variant
1082 // name exist after the markup, for example:
1083 // -{zh-hans:<span style="font-size:120%;">xxx</span>;zh-hant:\
1084 // <span style="font-size:120%;">yyy</span>;}-
1085 // we should split it as:
1087 // [0] => 'zh-hans:<span style="font-size:120%;">xxx</span>'
1088 // [1] => 'zh-hant:<span style="font-size:120%;">yyy</span>'
1092 foreach ( $this->mVariants
as $variant ) {
1093 // zh-hans:xxx;zh-hant:yyy
1094 $pat .= $variant . '\s*:|';
1095 // xxx=>zh-hans:yyy; xxx=>zh-hant:zzz
1096 $pat .= '[^;]*?=>\s*' . $variant . '\s*:|';
1099 $this->mVarSeparatorPattern
= $pat;
1101 return $this->mVarSeparatorPattern
;